package org.hepeng.fabric.gateway.event;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author he peng
 * @date 2022/3/30
 */
public abstract class CCEventListenerRegistry {

    private static final Map<CCEventDefinition , Set<CCEventListenerMethod>> EVENT_METHOD_MAP = new ConcurrentHashMap<>();

    public static synchronized void add(CCEventDefinition definition , CCEventListenerMethod eventListenerMethod) {
        if (Objects.isNull(definition) || Objects.isNull(eventListenerMethod)) {
            return;
        }

        Set<CCEventListenerMethod> methods;
        if (! EVENT_METHOD_MAP.containsKey(definition)) {
            methods = new HashSet<>();
        } else {
            methods = EVENT_METHOD_MAP.get(definition);
        }
        methods.add(eventListenerMethod);
        EVENT_METHOD_MAP.put(definition , methods);
    }

    public static Set<CCEventListenerMethod> getEventListenerMethods(CCEventDefinition definition) {
        return EVENT_METHOD_MAP.get(definition);
    }


    public static Set<String> getListeningChaincodes() {
        return EVENT_METHOD_MAP.keySet().stream().map(CCEventDefinition::getChaincode).collect(Collectors.toSet());
    }

    public static boolean hasListener() {
        return getListeningChaincodes().size() > 0;
    }
}
